package cn.dkdoo.redis.config;

import cn.dkdoo.utils.templateDefault.redis.DefaultRedisTemplate;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @author nicky
 * @date 2021/5/14 下午6:50
 */
@Configuration
public class RedisConfig {
    private static final Logger logger = LoggerFactory.getLogger(RedisConfig.class);
    public static final String defaultRedisTemplate = "defaultRedisTemplate";

    @Bean
    public JedisPoolConfig getRedisConfig() {
        JedisPoolConfig config = new JedisPoolConfig();
        return config;
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.redis.demo")
    public JedisConnectionFactory getConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setPoolConfig(getRedisConfig());
        return factory;
    }

    @Bean(name = defaultRedisTemplate)
    @Primary
    public DefaultRedisTemplate getRedisTemplate() {
        DefaultRedisTemplate template = new DefaultRedisTemplate(getConnectionFactory(), defaultRedisTemplate);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

        GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer =
                new GenericJackson2JsonRedisSerializer(om);
        StringRedisSerializer keySerializer = new StringRedisSerializer();

        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setKeySerializer(keySerializer);
        template.afterPropertiesSet();
        return template;
    }


//    @Bean(name = defaultRedisTemplate)
//    public DefaultRedisTemplate getDefaultRedisTemplate(JedisConnectionFactory redisTemplate) {
//        DefaultRedisTemplate template = new DefaultRedisTemplate(redisTemplate, defaultRedisTemplate);
//        return template;
//    }
}
